<template>
	<view class="wh bf">
		<view class="topimg p-r">
			<mg-img :src="`${onImgurl}img/sqbg.png`"></mg-img>
			<view class="p-a logoc">
				<mg-img :src="system.icon"></mg-img>
			</view>
		</view>
		<view class="snbtnc">
			<!-- #ifdef APP-PLUS || MP-TOUTIAO -->
			<button class="btni cf f-c f28" :style="{background:tColor,borderColor:tColor,}"
				@click="getUserInfo">用户登录</button>
			<!-- #endif -->
			<!-- #ifdef MP-BAIDU || MP-ALIPAY -->
			<button class="btni cf f-c f28" :style="{background:tColor,borderColor:tColor,}"
				:open-type="ptname?'getAuthorize':'getUserInfo'" @getuserinfo="mpGetUserInfo" scope='userInfo'
				@getAuthorize="onGetAuthorize">用户登录</button>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<button class="btni cf f-c f28" :style="{background:tColor,borderColor:tColor,}"
				@click="getUserProfile">用户登录</button>
			<!-- #endif -->
			
			<!-- line会员登录 -->
			<button class="btni cf f-c f28" :style="{background:'#01c854',borderColor:'#01c854',}"
				@click="getLineUserInfo"><img src="/static/line.png" alt="" style="" style="    width: 36px;
    height: 38px;
    margin-right: 5px;">会员登录</button>
			<button class="btni bf f-c f28" :style="{borderColor:tColor,color:tColor}" @click="gotourl()">返回个人中心</button>
		</view>
	</view>
</template>

<script>
	
import qs from 'qs';
import axios from 'axios';

	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	import utils from '@/common/utils.js'
	export default {
		name: 'sq-login',
		data() {
			return {
				resp: null,
				// line的配置信息,将你申请好的应用信息填到此处
				config: {
					channel_id: '',
					channel_secret: ''
				},
				access_token: '',
				
				
				loading: false,
				ptname: this.api.platform == 'ali'
			}
		},
		
		created() {
			// 当登录成功后回调会重新回到指定页面,所以我们在指定页面中判断是否是line登录
			let params = utils.getUrlParams(location.href);
			// 由于line登录在回调地址会携带code和state参数,所以我们可以使用这个判断
			if (params.code && params.state) {
				// alert('line 登录成功!');
				this.getLineToken();
			}
		},
		
		async onLoad() {
			
			// const config = await this.util.request({
			// 	url: this.api.config,
			// 	data: {
			// 		ident: 'system'
			// 	}
			// });
			// this.config.channel_id =  config.data.livine.client_id;
			// this.config.client_secret =  config.data.livine.client_secret;
			// console.log(config);
			this.util.setNT('登录')
		},
		methods: {
			gotourl()
			{
				this.go({
					t: 6,
					url: '/yb_wm/index/my-index'
				})
			},
			// 处理登录逻辑
			async handleLogin() {
				const configall = await this.util.request({
					url: this.api.config,
					data: {
						ident: 'system'
					}
				});
				
				
				const line_auth = 'https://access.line.me/oauth2/v2.1/authorize';
				const auth_params = {
					response_type: 'code',
					client_id: configall.data.livine.client_id,
					redirect_uri: window.location.href, // 在LINE Developers Console上注册的回调 URL 的 URL 编码字符串。您可以添加任何查询参数。
					state: 'STATE', // 用于防止跨站点请求伪造的唯一字母数字字符串. 您的网络应用应为每个登录会话生成一个随机值。这不能是 URL 编码的字符串。
					scope: 'profile openid email' // 向用户请求的权限,查询范围可以看官网(https://developers.line.biz/en/docs/line-login/integrate-line-login/#scopes)
				};
				console.log(auth_params);
				// 这里使用了qs处理参数
				const paramsString = qs.stringify(auth_params);
				window.location.href = `${line_auth}?${paramsString}`;
				console.log(`${line_auth}?${paramsString}`);
			},
			// 获取line的访问令牌
			async getLineToken() {
				const configall = await this.util.request({
					url: this.api.config,
					data: {
						ident: 'system'
					}
				});
				
				let paramsa = utils.getUrlParams(location.href);
				const params = {
					grant_type: 'authorization_code', // 固定值
					code: paramsa.code, // 从 LINE 平台收到的授权码
					client_id: configall.data.livine.client_id,
					client_secret:  configall.data.livine.client_secret,
					redirect_uri: window.location.origin + window.location.pathname+'?uniacid='+paramsa.uniacid+'#/yb_wm/other/sq-login' // 与授权请求redirect_uri中指定的值相同
				};
			
				const resp = await axios({
					url: 'https://api.line.me/oauth2/v2.1/token',
					method: 'post',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: params
				});
				if (resp.status === 200) {
					// 请求成功
					this.resp = resp.data;
					
					console.log(resp)
					// alert('获取到信息'+JSON.stringify(resp.data));
					this.access_token = resp.data.access_token;
					
					this.getLineUserInfo();
					
				}else{
					console.log(resp)
					alert('获取失败');
				}
			},
			async getLineUserInfo() {
				
				if (!this.access_token) {
					// alert('请先登录');
					this.handleLogin()
					return;
				}
				const resp = await axios({
					url: 'https://api.line.me/oauth2/v2.1/userinfo',
					headers: {
						Authorization: `Bearer ${this.access_token}`
					}
				});
				if (resp.status === 200) {
					// 请求成功
					// alert('点击用户信息,获取到信息'+JSON.stringify(resp.data));
					this.resp = resp.data;
					
					let portrait = '';
					let userName = this.resp.name;
					let lineopenid = this.resp.sub;
					
					this.util.request({
						'url': this.api.login,
						data: {
							lineopenid: lineopenid,
							userName:userName
						},
					}).then(res => {
						let userId = res.data.id;
						
						uni.setStorageSync('userId', userId)
						uni.setStorageSync('openid', lineopenid)
						uni.setStorageSync('userName', userName)
						this.refreshUser({
							storeId: this.storeid,
							portrait,
							userName,
							userId,
							now: 1,
						}).then(res => {
							this.util.message('登录成功', 1, 1000)
							
							this.gotourl();
						}).catch(() => {
							this.loading = false
						})
					})
					return;
					
					
				}else{
					console.log('getUserInfo fail', resp);
					uni.showModal({
						title: '温馨提示',
						content: '获取用户信息失败',
						showCancel: false
					});
				}
			},
			
			
			// 获取用户信息 API 在小程序可直接使用，在 5+App 里面需要先登录才能调用
			getUserInfo() {
				uni.getUserInfo({
					success: (result) => {
						// #ifdef MP-TOUTIAO
						let portrait = result.userInfo.avatarUrl,
							userName = result.userInfo.nickName,
							userId = this.uId
						// #endif
						this.refreshUser({
							storeId: this.storeid,
							portrait,
							userName,
							userId
						}).then(res => {
							this.$emit('refresh')
							this.util.message('登录成功', 1, 1000)
							utils.swnb(1000)
						})
						console.log('getUserInfo success', result);
					},
					fail: (error) => {
						console.log('getUserInfo fail', error);
						uni.showModal({
							title: '温馨提示',
							content: '获取头像等信息失败',
							showCancel: false
						});
					}
				});
			},
			getLineOpenId()
			{
				if (this.loading) return
				this.loading = true
				
			},
			getUserProfile() {
				if (this.loading) return
				this.loading = true
				uni.getUserProfile({
					desc: '用于完善用户资料',
					success: res => {
						try {
							if (res.errMsg == 'getUserProfile:ok') {
								let portrait = res.userInfo.avatarUrl,
									userName = res.userInfo.nickName,
									userId = this.uId
								this.refreshUser({
									storeId: this.storeid,
									portrait,
									userName,
									userId,
									now: 1,
								}).then(res => {
									this.util.message('登录成功', 1, 1000)
									utils.swnb(1000)
								}).catch(() => {
									this.loading = false
								})
								// console.log(portrait, userName, userId)
							}

						} catch (e) {
							this.loading = false
							console.log(e)
						}
					},
					fail: err => {
						this.loading = false
						uni.showModal({
							title: '温馨提示',
							content: '获取头像等信息失败',
							showCancel: false
						});
					}
				})
			},
			mpGetUserInfo(result) {
				if (this.loading) return
				this.loading = true
				console.log('mpGetUserInfo', result);
				if (result.detail.errMsg == 'getUserInfo:ok') {
					let portrait = result.detail.userInfo.avatarUrl,
						userName = result.detail.userInfo.nickName,
						userId = this.uId
					this.refreshUser({
						storeId: this.storeid,
						portrait,
						userName,
						userId,
						now: 1,
					}).then(res => {
						this.util.message('登录成功', 1, 1000)
						utils.swnb(1000)
					}).catch(() => {
						this.loading = false
					})
					// console.log(portrait, userName, userId)
				} else {
					this.loading = false
					uni.showModal({
						title: '温馨提示',
						content: '获取头像等信息失败',
						showCancel: false
					});
				}
			},
			onGetAuthorize(res) {
				// console.log('onGetAuthorize', res)
				my.getOpenUserInfo({
					fail: (res) => {},
					success: (res) => {
						// console.log('my.getOpenUserInfo', JSON.parse(res.response).response)
						let result = JSON.parse(res.response).response
						this.refreshUser({
							storeId: this.storeid,
							portrait: result.avatar,
							userName: result.nickName,
							userId: this.uId,
							now: 1,
						}).then(res => {
							this.util.message('登录成功', 1, 1000)
							utils.swnb(1000)
						})
					}
				});
			},
			mpGetphonenumber(result) {
				console.log('mpGetphonenumber', result);
				if (result.detail.errMsg == 'getPhoneNumber:ok') {
					let sessionKey = getApp().globalData.session_key,
						data = result.detail.encryptedData,
						iv = result.detail.iv,
						userId = this.uId
					this.util.request({
						url: this.api.jm,
						method: 'POST',
						data: {
							userId,
							sessionKey,
							data,
							iv
						}
					}).then(res => {
						res.data && this.$emit('refresh', res.data)
						this.refreshUser({
							get: 1,
						})
						console.log(res)
					})
					console.log(sessionKey, data, iv)
				} else {
					uni.showModal({
						title: '温馨提示',
						content: '授权手机号失败',
						showCancel: false
					});
					return;
				}
			}
		}
	}
</script>
<style scoped lang='scss'>
	.topimg {
		height: 100vw;
	}

	.logoc {
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 166rpx;
		height: 166rpx;
	}

	.snbtnc {
		margin-top: 95rpx;
	}

	.btni {
		margin: 0 19.5% 50rpx;
		border: 1px solid #000;
		height: 80rpx;
		border-radius: 80rpx;
	}
</style>
